package com.ruoyi.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.web.domain.PolicyCrawlArticle;
import com.ruoyi.web.domain.dto.PolicyCrawlArticleDto;
import com.ruoyi.web.domain.vo.PolicyCrawlArticleVo;
import com.ruoyi.web.mapper.PolicyCrawlArticleMapper;
import com.ruoyi.web.service.PolicyCrawlArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PolicyCrawlArticleServiceImpl extends ServiceImpl<PolicyCrawlArticleMapper, PolicyCrawlArticle> implements PolicyCrawlArticleService {

    @Autowired
    private PolicyCrawlArticleMapper policyCrawlArticleMapper;

    @Override
    public PolicyCrawlArticle selectByTitle(String articleTitle) {
        // 根据标题查询文章的实现
        LambdaQueryWrapper<PolicyCrawlArticle> wrapper = Wrappers.lambdaQuery(PolicyCrawlArticle.class)
                .eq(PolicyCrawlArticle::getArticleTitle, articleTitle);
        return this.getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePolicyCrawlArticleListBatch(List<PolicyCrawlArticle> articleList) {
        if (articleList != null && !articleList.isEmpty()) {
            // 默认批量保存数据量
            int DEFAULT_BATCH_SIZE = 200;
            if (articleList.size() <= DEFAULT_BATCH_SIZE) {
                // 直接保存
                this.saveBatch(articleList);
            } else {
                // 分批保存
                int totalSize = articleList.size();
                for (int i = 0; i < totalSize; i += DEFAULT_BATCH_SIZE) {
                    int end = Math.min(i + DEFAULT_BATCH_SIZE, totalSize);
                    List<PolicyCrawlArticle> batchList = articleList.subList(i, end);
                    this.saveBatch(batchList);
                }
            }
        }
    }

    @Override
    public List<PolicyCrawlArticleVo> findPolicyCrawlArticlePage(PolicyCrawlArticleDto policyCrawlArticleDto) {
        return policyCrawlArticleMapper.selectPolicyCrawlArticlePage(policyCrawlArticleDto);
    }

    @Override
    public PolicyCrawlArticleVo getPolicyCrawlArticleById(String baseId) {
        return policyCrawlArticleMapper.selectPolicyCrawlArticleById(baseId);
    }
}